package cn.xiaolang.common.utils;

import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;

/**
 * 二维码生成工具 
 * （导入com.google.zxing的jar包:core-java6-3.2.0-sources.jar）
 * @version 1.3
 * @since JDK1.7
 * @author fuhw
 * @company 上海浦信科技
 * @copyright (c) 2016 Puxin technology. All rights reserved.
 * @date 2016年11月8日 下午6:28:08
 */
public class QRCodeUtils {

	private static final int BLACK = 0xFF000000;
	private static final int WHITE = 0xFFFFFFFF;
	private static final int DEFAULT_WIDTH = 400;// 默认宽度
	private static final int DEFAULT_HEIGHT = 400;// 默认高度
	private static final int MIN_WIDTH = 50;// 最小宽度
	private static final int MIN_HEIGHT = 50;// 最小高度

	/**
	 * 生成二维码图片
	 * 
	 * @param content
	 *            二维码内容
	 * @param width
	 *            二维码图片宽度 min:50
	 * @param height
	 *            二维码图片高度 min:50
	 * @return 二维码图片
	 */
	public static BufferedImage getQRCode(String content, Integer width, Integer height) {
		try {
			if (width == null || height == null) {
				width = DEFAULT_WIDTH;
				height = DEFAULT_HEIGHT;
			} else if (width < MIN_WIDTH || height < MIN_HEIGHT) {
				width = MIN_WIDTH;
				height = MIN_HEIGHT;
			}
			MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
			Map<EncodeHintType, Object> hints = Maps.newHashMap();
			hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
			hints.put(EncodeHintType.MARGIN, 0);// 去除空白边缘
			BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, DEFAULT_WIDTH,
					DEFAULT_HEIGHT, hints);
			return toBufferedImage(bitMatrix);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 生成二维码图片 默认宽高 400
	 * 
	 * @param content
	 *            二维码内容
	 * @return 二维码图片
	 */
	public static BufferedImage getQRCode(String content) {
		return getQRCode(content, null, null);
	}

	public static BufferedImage toBufferedImage(BitMatrix matrix) {
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);

		for (int x = 0; x < width; x++) {
			for (int y = 0; y < height; y++) {
				image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
			}
		}
		return image;
	}

	/**
	 * 渲染图片加描述文字
	 *
	 * @param pressText
	 * @param qrFile
	 * @param fontStyle
	 * @param color
	 * @param fontSize
	 * @throws Exception
	 * 
	 * @author fuhw
	 * @date 2016年11月8日 下午4:41:00
	 */
	public static void pressText(String pressText, File qrFile, int fontStyle, Color color, int fontSize)
			throws Exception {
		pressText = new String(pressText.getBytes(), "utf-8");
		Image src = ImageIO.read(qrFile);
		int imageW = src.getWidth(null);
		int imageH = src.getHeight(null);
		BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
		Graphics g = image.createGraphics();
		g.drawImage(src, 0, 0, imageW, imageH, null);
		// 设置画笔的颜色
		g.setColor(color);
		// 设置字体
		Font font = new Font("宋体", fontStyle, fontSize);
		FontMetrics metrics = g.getFontMetrics(font);
		// 文字在图片中的坐标 这里设置在中间
		int startX = (DEFAULT_WIDTH - metrics.stringWidth(pressText)) / 2;
		int startY = DEFAULT_HEIGHT / 2;
		g.setFont(font);
		g.drawString(pressText, startX, startY);
		g.dispose();
		FileOutputStream out = new FileOutputStream(qrFile);
		ImageIO.write(image, "JPEG", out);
		out.close();
		System.out.println("image press success");
	}

	/**
	 * 去除图片的背景色
	 *
	 * @param path
	 * 
	 * @author fuhw
	 * @date 2016年11月8日 下午5:58:20
	 */
	public static void convert(String path) {
		try {
			BufferedImage image = ImageIO.read(new File(path));
			ImageIcon imageIcon = new ImageIcon(image);
			BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
					BufferedImage.TYPE_4BYTE_ABGR);
			Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
			g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
			int alpha = 0;
			for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
				for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
					int rgb = bufferedImage.getRGB(j2, j1);
					if (colorInRange(rgb))
						alpha = 0;
					else
						alpha = 255;
					rgb = (alpha << 24) | (rgb & 0x00ffffff);
					bufferedImage.setRGB(j2, j1, rgb);
				}
			}
			g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
			// 生成图片为PNG
			String outFile = path.substring(0, path.lastIndexOf("."));
			ImageIO.write(bufferedImage, "png", new File(outFile + ".png"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static int color_range = 210;

	public static boolean colorInRange(int color) {
		int red = (color & 0xff0000) >> 16;
		int green = (color & 0x00ff00) >> 8;
		int blue = (color & 0x0000ff);
		if (red >= color_range && green >= color_range && blue >= color_range)
			return true;
		return false;
	}
}
